{% extends "base.html" %}
{% load static %}
{% block title %}房间预订 - 风之宿{% endblock %}

{% block content %}
<div class="container mx-auto px-4 py-8">
  <h1 class="text-3xl font-bold text-primary mb-2">房间预订</h1>
  <p class="text-gray-600 mb-8">选择理想房间，开启舒适旅程</p>

  <!-- 搜索和筛选区域 -->
  <div class="bg-white rounded-xl shadow-md p-5 mb-8">
    <h2 class="text-xl font-semibold text-gray-800 mb-4">搜索房间</h2>
    <form id="search-form" method="GET" action="{% url 'user:search_rooms' %}" class="space-y-4">
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        <!-- 入住日期 -->
        <div>
          <label for="check-in" class="block text-sm font-medium text-gray-700 mb-1">入住日期</label>
          <input type="date" id="check-in" name="check_in" min="{{ default_check_in }}"
                  value="{{ search_params.check_in }}"
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-primary focus:border-primary">
        </div>
        
        <!-- 退房日期 -->
        <div>
          <label for="check-out" class="block text-sm font-medium text-gray-700 mb-1">退房日期</label>
          <input type="date" id="check-out" name="check_out"
                  value="{{ search_params.check_out }}"
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-primary focus:border-primary">
        </div>
        
        <!-- 入住人数 -->
        <div>
          <label for="guests" class="block text-sm font-medium text-gray-700 mb-1">入住人数</label>
          <select id="guests" name="guests"
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-primary focus:border-primary">
            <option value="" {% if not search_params.guests %}selected{% endif %}>不限</option>
            <option value="1" {% if search_params.guests == '1' %}selected{% endif %}>1人</option>
            <option value="2" {% if search_params.guests == '2' %}selected{% endif %}>2人</option>
            <option value="3" {% if search_params.guests == '3' %}selected{% endif %}>3人</option>
            <option value="4" {% if search_params.guests == '4' %}selected{% endif %}>4人</option>
            <option value="5" {% if search_params.guests == '5' %}selected{% endif %}>5人以上</option>
          </select>
        </div>
        
        <!-- 排序方式 -->
        <div>
          <label for="sort-by" class="block text-sm font-medium text-gray-700 mb-1">排序方式</label>
          <select id="sort-by" name="sort_by"
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-primary focus:border-primary">
            <option value="default" {% if search_params.sort_by == 'default' %}selected{% endif %}>推荐排序</option>
            <option value="price_asc" {% if search_params.sort_by == 'price_asc' %}selected{% endif %}>价格从低到高</option>
            <option value="price_desc" {% if search_params.sort_by == 'price_desc' %}selected{% endif %}>价格从高到低</option>
            <option value="popularity" {% if search_params.sort_by == 'popularity' %}selected{% endif %}>热门优先</option>
            <option value="capacity_asc" {% if search_params.sort_by == 'capacity_asc' %}selected{% endif %}>容量从小到大</option>
            <option value="capacity_desc" {% if search_params.sort_by == 'capacity_desc' %}selected{% endif %}>容量从大到小</option>
          </select>
        </div>
        
        <!-- 关键词搜索 -->
        <div class="lg:col-span-3">
          <label for="search-keyword" class="block text-sm font-medium text-gray-700 mb-1">关键词</label>
          <div class="relative">
            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
              <i class="fa fa-search text-gray-400"></i>
            </div>
            <input type="text" id="search-keyword" name="keyword"
                  value="{{ search_params.keyword }}"
                  class="pl-10 w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-primary focus:border-primary"
                  placeholder="搜索房间名称、类型或设施">
          </div>
        </div>

        <!-- 价格范围 -->
        <div>
          <label for="price-range" class="block text-sm font-medium text-gray-700 mb-1">价格范围</label>
          <select id="price-range" name="price_range"
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-primary focus:border-primary">
            <option value="all" {% if search_params.price_range == 'all' %}selected{% endif %}>所有价格</option>
            <option value="0-200" {% if search_params.price_range == '0-200' %}selected{% endif %}>¥200以下</option>
            <option value="200-500" {% if search_params.price_range == '200-500' %}selected{% endif %}>¥200-¥500</option>
            <option value="500-1000" {% if search_params.price_range == '500-1000' %}selected{% endif %}>¥500-¥1000</option>
            <option value="1000+" {% if search_params.price_range == '1000+' %}selected{% endif %}>¥1000以上</option>
          </select>
        </div>

        <!-- 房间类型 -->
        <div>
          <label for="room-type" class="block text-sm font-medium text-gray-700 mb-1">房间类型</label>
          <select id="room-type" name="room_type"
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-primary focus:border-primary">
            <option value="all" {% if search_params.room_type == 'all' %}selected{% endif %}>所有类型</option>
            <option value="standard" {% if search_params.room_type == 'standard' %}selected{% endif %}>标准间</option>
            <option value="deluxe" {% if search_params.room_type == 'deluxe' %}selected{% endif %}>豪华间</option>
            <option value="suite" {% if search_params.room_type == 'suite' %}selected{% endif %}>套房</option>
            <option value="game" {% if search_params.room_type == 'game' %}selected{% endif %}>电竞房</option>
            <option value="family" {% if search_params.room_type == 'family' %}selected{% endif %}>家庭房</option>
          </select>
        </div>

        <!-- 容纳人数 -->
        <div>
          <label for="capacity" class="block text-sm font-medium text-gray-700 mb-1">容纳人数</label>
          <select id="capacity" name="capacity"
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-primary focus:border-primary">
            <option value="all" {% if search_params.capacity == 'all' %}selected{% endif %}>不限</option>
            <option value="1" {% if search_params.capacity == '1' %}selected{% endif %}>1人</option>
            <option value="2" {% if search_params.capacity == '2' %}selected{% endif %}>2人</option>
            <option value="3" {% if search_params.capacity == '3' %}selected{% endif %}>3-4人</option>
            <option value="5+" {% if search_params.capacity == '5+' %}selected{% endif %}>5人以上</option>
          </select>
        </div>
      </div>

      <div class="flex flex-wrap gap-3 justify-end">
        <button type="button" id="reset-filter" class="px-4 py-2 border border-gray-300 text-gray-700 rounded-md hover:bg-gray-50 transition-colors">
          重置筛选
        </button>
        <button type="submit" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90 transition-colors">
          <i class="fa fa-search mr-1"></i> 搜索房间
        </button>
      </div>
    </form>
  </div>

  <div class="grid grid-cols-1 lg:grid-cols-5 gap-8">
    <!-- 房间列表 - 占据更大空间以突出展示 -->
    <div class="lg:col-span-3">
      <div class="bg-white rounded-xl shadow-md overflow-hidden transition-shadow hover:shadow-lg">
        <div class="p-6 border-b border-gray-100 flex flex-wrap justify-between items-center">
          <div>
            <h2 class="text-2xl font-semibold text-gray-800">可选房间</h2>
            <p class="text-gray-500 mt-1">
              从 <span class="font-medium">{% if total_available %}{{ total_available }}{% else %}{{ room_data|length }}{% endif %}</span> 个可用房间中找到 
              <span class="font-medium text-primary">{% if total_matched %}{{ total_matched }}{% else %}{{ room_data|length }}{% endif %}</span> 个匹配房间
              {% if search_params.keyword or search_params.price_range != 'all' or search_params.room_type != 'all' or search_params.capacity != 'all' or search_params.check_in or search_params.check_out or search_params.guests %}
                <span class="ml-2">(已应用筛选条件)</span>
              {% endif %}
            </p>
          </div>
          <div class="mt-3 sm:mt-0">
            <span id="room-count" class="text-sm text-gray-600">显示 {{ room_data|length }} 个房间</span>
          </div>
        </div>

        <div class="divide-y divide-gray-100">
          {% for item in room_data %}
          <div class="p-6 hover:bg-gray-50 transition-colors room-item"
               data-name="{{ item.room.name|lower }}"
               data-price="{{ item.room.price }}"
               data-type="{{ item.room.room_type|lower }}"
               data-capacity="{{ item.room.capacity }}">
            <div class="flex flex-col md:flex-row gap-6">
              <!-- 房间图片 -->
              <div class="md:w-1/3 lg:w-1/4">
                <div class="rounded-lg overflow-hidden h-40 md:h-full bg-gray-100 relative group">
                  <!-- 房间状态标签 -->
                  <div class="absolute top-3 left-3 z-10">
                    {% if item.room.status == 'available' %}
                      <span class="px-2 py-1 bg-green-500 text-white text-xs rounded-md shadow-sm">
                        可预订
                      </span>
                    {% elif item.room.status == 'booked' %}
                      <span class="px-2 py-1 bg-red-500 text-white text-xs rounded-md shadow-sm">
                        已预订
                      </span>
                    {% elif item.room.status == 'maintenance' %}
                      <span class="px-2 py-1 bg-yellow-500 text-white text-xs rounded-md shadow-sm">
                        维护中
                      </span>
                    {% endif %}
                  </div>

                  {% if item.room.image_url %}
                    <img src="{% static 'uploads/' %}{{ item.room.image_url }}"
                         alt="{{ item.room.name }}"
                         class="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110">
                  {% else %}
                    <img src="{% static 'images/default.jpeg' %}"
                         alt="默认房间图片"
                         class="w-full h-full object-cover">
                  {% endif %}
                </div>
              </div>

              <!-- 房间信息 -->
              <div class="md:w-2/3 lg:w-3/4">
                <div class="flex flex-col md:flex-row md:justify-between gap-2">
                  <div>
                    <h3 class="text-xl font-semibold text-gray-800">{{ item.room.name }}</h3>
                    <div class="flex items-center mt-1">
                      <span class="text-sm text-gray-500 mr-3">容纳 {{ item.room.capacity }} 人</span>
                      <span class="text-sm px-2 py-0.5 bg-gray-100 text-gray-600 rounded">
                        {{ item.room.room_type }}
                      </span>
                    </div>
                  </div>
                  <div class="text-right">
                    <span class="text-primary font-bold text-xl">¥{{ item.room.price }}</span>
                    <span class="text-gray-500 text-sm">/晚</span>
                  </div>
                </div>
                
                <!-- 如果选择了日期，显示总价信息 -->
                {% if item.nights > 0 and item.total_price %}
                <div class="mb-3 p-3 bg-blue-50 rounded-lg">
                  <div class="flex justify-between text-sm">
                    <span class="text-gray-700">{{ item.nights }}晚总价:</span>
                    <span class="font-bold text-primary text-lg">¥{{ item.total_price }}</span>
                  </div>
                </div>
                {% endif %}

                <p class="text-gray-600 mt-3 text-sm line-clamp-2">{{ item.room.description }}</p>
                <!-- 房间设施 -->
                <div class="mt-4 flex flex-wrap gap-2">
                  {% if item.room.amenities %}
                    <span class="px-2 py-1 bg-gray-100 text-gray-700 text-xs rounded-full">
                      {{ item.room.amenities }}
                    </span>
                  {% endif %}
                </div>

                <!-- 选择按钮 -->
                <div class="mt-4">
                  <button type="button"
                          class="select-room-btn px-4 py-2 border border-primary text-primary rounded-md hover:bg-primary hover:text-white transition-colors text-sm font-medium {% if item.room.status != 'available' %}opacity-50 cursor-not-allowed{% endif %}"
                          data-room-id="{{ item.room.id }}"
                          data-room-name="{{ item.room.name }}"
                          data-room-price="{{ item.room.price }}"
                          {% if item.room.status != 'available' %}disabled{% endif %}>
                    {% if item.room.status == 'available' %}选择此房间{% else %}不可预订{% endif %}
                  </button>
                </div>
              </div>
            </div>
          {% endfor %}
        </div>
        
        <!-- 无结果提示 -->
          <div id="no-results" class="p-12 text-center hidden">
            <i class="fa fa-search text-gray-300 text-5xl mb-4"></i>
            <h3 class="text-xl font-medium text-gray-700 mb-2">未找到符合条件的房间</h3>
            <p class="text-gray-500">请尝试调整搜索条件</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 预订表单和信息 - 固定位置便于填写 -->
    <div class="lg:col-span-2">
      <div class="sticky top-6">
        <!-- 预订表单卡片 -->
        <div class="bg-white rounded-xl shadow-md p-6 mb-6">
          <h2 class="text-xl font-semibold text-gray-800 mb-5">预订信息</h2>

          <form method="POST" action="{% url 'user:search_rooms' %}" class="space-y-5" id="booking-form">
              {% csrf_token %}
              
              <!-- 显示消息提示 -->
              {% if messages %}
                {% for message in messages %}
                  <div class="px-4 py-3 rounded-md {% if message.tags == 'error' %}bg-red-50 text-red-700{% elif message.tags == 'warning' %}bg-yellow-50 text-yellow-700{% else %}bg-green-50 text-green-700{% endif %}">
                    {{ message }}
                  </div>
                {% endfor %}
              {% endif %}
              
              <div>
                <label for="room_id" class="block text-sm font-medium text-gray-700 mb-1">已选房间</label>
                <div class="relative">
                  <input type="text" id="selected_room_display" readonly
                         class="w-full px-3 py-2 border border-gray-300 rounded-md bg-gray-50 text-gray-900"
                         placeholder="请从左侧选择房间">
                  <input type="hidden" id="room_id" name="room_id" required>
                  <div id="room-error" class="hidden text-red-500 text-xs mt-1">请选择一个房间</div>
                </div>
              </div>

              <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                  <label for="check_in" class="block text-sm font-medium text-gray-700 mb-1">入住日期</label>
                  <input type="date" id="check_in" name="check_in" required
                         class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-primary focus:border-primary">
                  <div id="check-in-error" class="hidden text-red-500 text-xs mt-1">请选择有效的入住日期</div>
                </div>

                <div>
                  <label for="check_out" class="block text-sm font-medium text-gray-700 mb-1">退房日期</label>
                  <input type="date" id="check_out" name="check_out" required
                         class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-primary focus:border-primary">
                  <div id="check-out-error" class="hidden text-red-500 text-xs mt-1">退房日期必须晚于入住日期</div>
                </div>
              </div>

              <div>
                <label for="guests" class="block text-sm font-medium text-gray-700 mb-1">入住人数</label>
                <input type="number" id="guests" name="guests" min="1" max="10" required
                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-primary focus:border-primary"
                       placeholder="入住人数" value="2">
                <div id="guests-error" class="hidden text-red-500 text-xs mt-1">请输入有效的人数</div>
                <div id="capacity-warning" class="hidden text-yellow-500 text-xs mt-1">人数超出房间容量</div>
              </div>

            <!-- 预订信息预览 -->
            <div class="bg-gray-50 p-4 rounded-lg">
              <h3 class="font-medium text-gray-800 mb-3">预订详情</h3>
              <div class="space-y-2 text-sm">
                <div class="flex justify-between">
                  <span class="text-gray-600">房间价格:</span>
                  <span id="price_display" class="text-gray-800">¥0/晚</span>
                </div>
                <div class="flex justify-between">
                  <span class="text-gray-600">入住天数:</span>
                  <span id="days_display" class="text-gray-800">0天</span>
                </div>
                <div class="border-t border-gray-200 my-2 pt-2 flex justify-between font-medium">
                  <span class="text-gray-700">总计:</span>
                  <span id="total_display" class="text-primary">¥0</span>
                </div>
              </div>
            </div>

            <button type="submit" class="w-full bg-primary text-white py-3 px-4 rounded-md hover:bg-primary/90 transition-colors font-semibold shadow-sm hover:shadow">
              确认预订
            </button>
          </form>
        </div>

        <!-- 预订须知卡片 -->
        <div class="bg-white rounded-xl shadow-md p-6">
          <h3 class="text-lg font-semibold text-gray-800 mb-3">预订须知</h3>
          <ul class="space-y-2 text-sm text-gray-600">
            <li class="flex items-start">
              <i class="fas fa-info-circle text-primary mt-0.5 mr-2"></i>
              <span>入住时间为下午14:00后，退房时间为中午12:00前</span>
            </li>
            <li class="flex items-start">
              <i class="fas fa-info-circle text-primary mt-0.5 mr-2"></i>
              <span>如需提前入住或延迟退房，请提前联系我们</span>
            </li>
            <li class="flex items-start">
              <i class="fas fa-info-circle text-primary mt-0.5 mr-2"></i>
              <span>预订后如需取消，请至少在入住前24小时通知</span>
            </li>
            <li class="flex items-start">
              <i class="fas fa-info-circle text-primary mt-0.5 mr-2"></i>
              <span>房间价格已包含服务费和税费</span>
            </li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
  // 获取DOM元素
  const checkInInput = document.getElementById('check_in');
  const checkOutInput = document.getElementById('check_out');
  const roomIdInput = document.getElementById('room_id');
  const selectedRoomDisplay = document.getElementById('selected_room_display');
  const priceDisplay = document.getElementById('price_display');
  const daysDisplay = document.getElementById('days_display');
  const totalDisplay = document.getElementById('total_display');
  const guestsInput = document.getElementById('guests');
  const bookingForm = document.getElementById('booking-form');
  const selectRoomBtns = document.querySelectorAll('.select-room-btn');
  const searchForm = document.getElementById('search-form');
  const resetFilterBtn = document.getElementById('reset-filter');
  const roomItems = document.querySelectorAll('.room-item');
  const roomCountEl = document.getElementById('room-count');
  const noResultsEl = document.getElementById('no-results');
  
  // 错误提示元素
  const roomError = document.getElementById('room-error');
  const checkInError = document.getElementById('check-in-error');
  const checkOutError = document.getElementById('check-out-error');
  const guestsError = document.getElementById('guests-error');
  const capacityWarning = document.getElementById('capacity-warning');
  
  // 存储当前选择的房间信息
  let currentRoomPrice = 0;
  let currentRoomCapacity = 0;

  // 检查是否有预选中的房间
  const preselectedRoomId = {% if preselected_room %}{{ preselected_room.id }}{% else %}null{% endif %};

  // 设置最小日期为今天
  const today = new Date().toISOString().split('T')[0];
  checkInInput.min = today;
  checkOutInput.min = today;

  // 设置默认日期（如果搜索参数中有日期则使用，否则使用默认值）
  if (!checkInInput.value) {
    checkInInput.value = '{{ default_check_in }}';
  }
  if (!checkOutInput.value) {
    checkOutInput.value = '{{ default_check_out }}';
  }

  // 当入住日期改变时，更新退房日期的最小值
  function updateMinCheckOutDate() {
    if (checkInInput.value) {
      checkOutInput.min = checkInInput.value;
      // 如果当前退房日期早于或等于新的入住日期，自动调整
      if (checkOutInput.value <= checkInInput.value) {
        const nextDay = new Date(checkInInput.value);
        nextDay.setDate(nextDay.getDate() + 1);
        checkOutInput.value = nextDay.toISOString().split('T')[0];
      }
    }
    validateForm();
    calculateTotal();
  }

  // 计算总价和天数
  function calculateTotal() {
    if (!currentRoomPrice || !checkInInput.value || !checkOutInput.value) {
      daysDisplay.textContent = '0天';
      totalDisplay.textContent = '¥0';
      priceDisplay.textContent = '¥0/晚';
      return;
    }
    
    const checkInDate = new Date(checkInInput.value);
    const checkOutDate = new Date(checkOutInput.value);
    
    // 计算天数差异
    const timeDiff = checkOutDate - checkInDate;
    const nights = Math.ceil(timeDiff / (1000 * 3600 * 24));
    
    // 确保天数为正数
    if (nights <= 0) {
      daysDisplay.textContent = '0天';
      totalDisplay.textContent = '¥0';
      return;
    }
    
    // 计算总价
    const totalPrice = currentRoomPrice * nights;
    
    // 更新显示
    priceDisplay.textContent = `¥${currentRoomPrice}/晚`;
    daysDisplay.textContent = `${nights}天`;
    totalDisplay.textContent = `¥${totalPrice.toFixed(2)}`;
  }

  // 表单验证
  function validateForm() {
    let isValid = true;
    
    // 隐藏所有错误信息
    roomError.classList.add('hidden');
    checkInError.classList.add('hidden');
    checkOutError.classList.add('hidden');
    guestsError.classList.add('hidden');
    capacityWarning.classList.add('hidden');
    
    // 验证房间选择
    if (!roomIdInput.value) {
      roomError.classList.remove('hidden');
      isValid = false;
    }
    
    // 验证入住日期
    if (!checkInInput.value) {
      checkInError.classList.remove('hidden');
      isValid = false;
    }
    
    // 验证退房日期
    if (!checkOutInput.value) {
      checkOutError.classList.remove('hidden');
      isValid = false;
    } else if (checkOutInput.value <= checkInInput.value) {
      checkOutError.classList.remove('hidden');
      isValid = false;
    }
    
    // 验证入住人数
    const guests = parseInt(guestsInput.value);
    if (isNaN(guests) || guests < 1) {
      guestsError.classList.remove('hidden');
      isValid = false;
    } else if (currentRoomCapacity > 0 && guests > currentRoomCapacity) {
      capacityWarning.classList.remove('hidden');
      isValid = false;
    }
    
    return isValid;
  }

  // 房间选择按钮点击事件
  selectRoomBtns.forEach(btn => {
    btn.addEventListener('click', function() {
      if (this.disabled) return;

      const roomId = this.getAttribute('data-room-id');
      const roomName = this.getAttribute('data-room-name');
      const roomPrice = parseFloat(this.getAttribute('data-room-price'));
      // 从closest的room-item中获取容量信息
      const roomItem = this.closest('.room-item');
      const roomCapacity = roomItem ? parseInt(roomItem.getAttribute('data-capacity')) : 0;

      // 更新表单值
      roomIdInput.value = roomId;
      selectedRoomDisplay.value = `${roomName} (容纳${roomCapacity}人)`;
      currentRoomPrice = roomPrice;
      currentRoomCapacity = roomCapacity;
      
      // 如果当前人数超出新选择房间的容量，自动调整
      const currentGuests = parseInt(guestsInput.value);
      if (currentGuests > roomCapacity) {
        guestsInput.value = roomCapacity;
      }

      // 重新计算总价
      calculateTotal();
      
      // 验证表单
      validateForm();

      // 高亮显示选中的房间
      document.querySelectorAll('.room-item').forEach(roomEl => {
        roomEl.classList.remove('ring-2', 'ring-primary', 'ring-opacity-50', 'bg-blue-50');
      });
      roomItem.classList.add('ring-2', 'ring-primary', 'ring-opacity-50', 'bg-blue-50');
      
      // 滚动到预订表单
      document.getElementById('booking-form').scrollIntoView({ behavior: 'smooth', block: 'nearest' });
    });
  });

  // 如果有预选中的房间，自动触发选择
  if (preselectedRoomId) {
    setTimeout(() => {
      const preselectedBtn = document.querySelector(`.select-room-btn[data-room-id="${preselectedRoomId}"]`);
      if (preselectedBtn && !preselectedBtn.disabled) {
        preselectedBtn.click();
      }
    }, 100); // 稍微延迟以确保DOM完全加载
  }

  // 添加事件监听器
  checkInInput.addEventListener('change', updateMinCheckOutDate);
  checkOutInput.addEventListener('change', validateForm);
  checkOutInput.addEventListener('change', calculateTotal);
  guestsInput.addEventListener('input', validateForm);
  
  // 表单提交前验证
  if (bookingForm) {
    bookingForm.addEventListener('submit', function(e) {
      if (!validateForm()) {
        e.preventDefault();
        // 滚动到第一个错误位置
        const firstError = document.querySelector('.text-red-500:not(.hidden)');
        if (firstError) {
          firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
      }
    });
  }

  // 初始化计算总价
  calculateTotal();

  // 搜索表单提交事件 - 直接提交到服务器
  searchForm.addEventListener('submit', function(e) {
    // 让表单正常提交到服务器进行筛选
    // 不阻止默认行为，让Django后端处理筛选逻辑
  });

  // 重置筛选按钮事件
  resetFilterBtn.addEventListener('click', function() {
    // 重置表单并重新加载页面
    window.location.href = '{% url "user:search_rooms" %}';
  });

  // 添加事件监听器
  checkInInput.addEventListener('change', updateMinCheckOutDate);
  checkOutInput.addEventListener('change', validateForm);
  checkOutInput.addEventListener('change', calculateTotal);
  guestsInput.addEventListener('input', validateForm);
  guestsInput.addEventListener('input', calculateTotal);
  
  // 表单提交前验证
  if (bookingForm) {
    bookingForm.addEventListener('submit', function(e) {
      if (!validateForm()) {
        e.preventDefault();
        // 滚动到第一个错误位置
        const firstError = document.querySelector('.text-red-500:not(.hidden)');
        if (firstError) {
          firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
      }
    });
  }

  // 如果有预选中的房间，自动触发选择
  if (preselectedRoomId) {
    setTimeout(() => {
      const preselectedBtn = document.querySelector(`.select-room-btn[data-room-id="${preselectedRoomId}"]`);
      if (preselectedBtn && !preselectedBtn.disabled) {
        preselectedBtn.click();
      }
    }, 100);
  }

  // 初始化计算总价
  calculateTotal();
});
</script>
{% endblock %}